package indi.caspar.algorithms.binTree;

import java.util.ArrayList;
import java.util.List;

/**
 * 二叉树
 * Created by casparhuan on 2017/3/4.
 */
public class BinaryTree1 {

    private List<Node> nodeList = null;
    public static int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };//example


    public static void main(String[] args) {
        BinaryTree1 tree1 = new BinaryTree1(array);
        tree1.middleOrderTraverse(tree1.nodeList.get(0));
    }

    public BinaryTree1(){
        nodeList = new ArrayList<Node>();
    }

    public BinaryTree1(List<Node> nodeList){
        nodeList = nodeList;
    }

    public BinaryTree1(int[] array){
        nodeList = new ArrayList<Node>();
        for (int i = 0; i < array.length; i++) {
            nodeList.add(new Node(array[i],null,null));
        }

        for (int i = 0; i < array.length/2   ; i++) {
            nodeList.get(i).leftChild = nodeList.get(2*i + 1);
            nodeList.get(i).rightChild = nodeList.get(2*i + 2);
        }
    }

   public void addNode(Node node){
       nodeList.add(node);
   }

    public void preOrderTraverse(Node node){
        if (node==null){
            return;
        }
        System.out.print(node.data+  "  ");
        preOrderTraverse(node.leftChild);
        preOrderTraverse(node.rightChild);
    }

    public void middleOrderTraverse(Node node){
        if (node==null){
            return;
        }
        middleOrderTraverse(node.leftChild);
        System.out.print(node.data+  "  ");
        middleOrderTraverse(node.rightChild);
    }

    public void postOrderTraverse(Node node){
        if (node==null){
            return;
        }
        postOrderTraverse(node.leftChild);
        postOrderTraverse(node.rightChild);
        System.out.print(node.data+  "  ");
    }

    private static class Node{
        Node leftChild;
        Node rightChild;
        int data;

        Node(){
            this(0,null,null);
        }
        Node(int data){
            this(data,null,null);
        }

        Node(int data,Node leftChild){
            this(data,leftChild,null);
        }

        Node(int data,Node leftChild,Node rightChild){
            super();
            this.data = data;
            this.leftChild = leftChild;
            this.rightChild = rightChild;
        }
    }
}
